<?php
include("../UserIncludes/DbConfig.php");
$mdid=$_REQUEST['advertiseid'];
if($mdid=='')$mdid='c4ca4238a0b923820dcc509a6f75849b'; // For debug


$SQL_NET="SELECT  N.`networkId`,M.`adsiteId`, D.`allowNetwork` FROM  `adspace_master` M, `adspace_details` D, `network_sites` N, `network_master` NM WHERE M.`adspaceId`=D.`adspaceId` AND D.`adspaceIdMd`='".$mdid."' AND N.`siteId`=M.`adsiteId` AND NM.`networkId`=N.`networkId` AND NM.`networkType`=D.`adspaceType`";
$RS_NET=mysql_query($SQL_NET) or die("Error !! #1=>".mysql_error());
while($ROW_NET=mysql_fetch_array($RS_NET)){
	$nets[]=$ROW_NET[networkId];	
}
echo "<pre>";
print_r($nets);
echo "</pre>";

//$path_offset="/admobweb_new/";
$path="http://".$_SERVER['HTTP_HOST'];
$path=$path.$path_offset;

$SQL_main="SELECT AP.`adspaceId`, AP.`adsiteId`, `AS`.`ctr_grade`, AD.* FROM `adsite_master` `AS`,`adspace_master` AP, `adspace_details` AD WHERE AD.`adspaceId`=AP.`adspaceId` AND `AS`.`adsiteId`=AP.`adsiteId` AND AP.`adspaceIdMd`='".$mdid."' AND AP.`status`='Y'";
$RS_main=mysql_query($SQL_main) or die("Error at line ".__LINE__."SQL:".mysql_error());
if(mysql_num_rows($RS_main)){		
	$ROW_main=mysql_fetch_assoc($RS_main) or die("Error at line ".__LINE__."SQL:".mysql_error());
	$sp=$ROW_main['adspaceId'];  // adspace id
	$adsiteId=$ROW_main['adsiteId'];
	$ctr_grade=$ROW_main[ctr_grade];  // Site's CTR grade (A,B,C,D,E)
	#######################################
	$ads=array();// store ads
	###############################################	
	#################Get ads#######################	
	###############################################		
	$queryGetAds.=" SELECT AD.*,SD.*,AM.* FROM advertise_details AD, adspace_details SD,advertise_master AM";
	$queryGetAds.=" WHERE AD.adspaceId=SD.adspaceId AND AD.advertiseId=AM.advertiseId AND SD.adspaceIdMd='".$mdid."' ";
	$queryGetAds.=" AND AM.startDate <= CURDATE() AND AM.endDate >= CURDATE()";
	$queryGetAds.=" AND AM.advertiseStatus = 'Y' ";	
	
	$result=mysql_query($queryGetAds);
	$RowsAds = array();
	while($row = mysql_fetch_assoc($result))
	{
		$RowsAds[] = $row;	
	}
	$activeAds =array();
	###################End get Ads#################
	switch(strtolower($ROW_main['adspaceType']))
	{
		default:		
		case "text":// for text ads		
			$alignment =strtolower($ROW_main[thumbOrientation]);
			$cellSpacing = 6;
			$cellPadding = 6;
			$adsno =$ROW_main[noOfTextAd];							
			$rows = 1;// number of rows as default
			$cols = 1;// number of cols as default		
			if($alignment=='horizontal')$cols =$adsno;
			else $rows = $adsno;			
			$sizes =explode("x", $ROW_main[adSize]);// get dimension of ad			
			$totalWidth = $sizes[0];
			$totalHeight = $sizes[1];				
			$titleFontSize = "12px";
			$descriptionFontSize = "11px";		
			// specialy  cols & rows base on ad's dimension
			switch ($ROW_main[adSize]) {
				case "184x360" :
					$adsno = 5;
					$rows = 5;					
					break;
				case "468x60" :
					$adsno = 2;					
					$alignment = "horizontal";
					$cols = 2;					
					break;
				case "234x60" :
					$adsno = 1;										
					break;
				case "728x90" :
					$adsno = 5;
					$alignment = "horizontal";
					$cols = 5;					
					break;
				case "125x125" :
					$adsno = 1;
					$cellSpacing = 0;					
					break;
				case "120x240" :
					$adsno = 3;
					$rows = 3;					
					break;
				case "180x150" :
					$adsno = 1;					
					break;
				case "300x250" :
					$adsno = 4;
					$cols = 2;
					$rows = 2;
					break;
				case "336x280" :
					$adsno = 6;
					$cols = 3;
					$rows = 2;
					break;
				case "250x250" :
					$adsno = 4;
					$cols = 2;
					$rows = 2;
					break;
				case "120x600" :
					$adsno = 6;
					$rows = 6;
					break;
				case "160x600" :
					$adsno = 7;
					$rows = 7;
					break;
				default :					
					break;
			}			
			$width=intval($totalWidth/$cols);
			$height=intval($totalHeight/$rows);
			// get attributes of text ad with default values if that is not exist.
			if($ROW_main[fontType]!=""){
				$fontType=$ROW_main[fontType];
			}else{
				$fontType="Arial";
			}
			if($ROW_main[backgroundColor]!=""){
				$backgroundColor=$ROW_main[backgroundColor];
			}else{
				$backgroundColor="#E8E8E8";
			}
			//echo $backgroundColor;
			if($ROW_main[headerColor]!=""){
				$headerColor=$ROW_main[headerColor];
			}else{
				$headerColor="#E8E8E8";
			}
			//echo $headerColor;
			if($ROW_main[bodyColor]!=""){
				$bodyColor=$ROW_main[bodyColor];
			}else{
				$bodyColor="#000000";
			}
			// render HTML
			//-- get ads list will be show.
			$c=0;$r=0;$i=0;
			$html='';
			$htmlstart='<table width="'.$totalWidth.'" height="'.$totalHeight.'" border="0" cellspacing="'.$cellSpacing.'"><tr>';
			$htmlend='</table>';
			##############get ads#######################
			
			############################################						
			if(count($RowsAds)==0)
			{
				$default=array();				
				$default[adTitle_personal]='Title personal goes here ';
				$default[adTitle]='Title gose here ';	
				$default[advertiseId]='0';		
				$RowsAds[]=$default;
			}
			$actView = array();
			foreach($RowsAds as $ROW){				
				if($ROW[adTitle_personal]=="")$ROW[adTitle_personal]="No description avail..";
				
				if($c<$cols){					
					$html.='<td><table width="'.$width.'" height="'.$height.'" border="0" cellspacing="'.$cellSpacing.'" cellpadding="6" bgcolor="'.$backgroundColor.'">
							<tr><td align="center"><a href="'.$path.'/wbk/wbk.php?bk='.__randit().$ROW[advertiseId].__randit().'&s='.__randit().$sites[0].__randit().'&val='.$mdid.'" style="text-decoration:none;"><font color="'.$headerColor.'" style="font-family: '.$fontType.';">'.$ROW[adTitle].'</font><br><br><font color="'.$bodyColor.'" style="font-family: '.$fontType.';">'.$ROW[adTitle_personal].'</font></a></td></tr>
							</table></td>';
					$c++;
					$actView[]=$row[advertiseId];
				}
				
				if($c==$cols){
					$html.='</tr><tr>';
					$r++;
					$c=0;					
				}
				//if($r==$rows){
				if($adsno>0&&$i%$adsno==0)
				{
					$ads[]=htmlentities($htmlstart.$html.$htmlend);
					$activeAds[]= $actView;
					$actView=array();
					$html="";
					$r=0;
				}	
			} // End of While		
			$script= "<script language='javascript'>				
					var DOC = top.document;														
					frame=DOC.getElementById('iframe$mdid');
					frame.style.height=$totalHeight;
					frame.style.width=$totalWidth;
					</script>";
			$script=htmlentities($script);
			break;
		case "banner":// for banner ads
			//echo "Missing code for generating banner";
			$sizes =explode("x", $ROW_main[adSize]);// get dimension of ad		
			$width=$sizes[0];
			$height=$sizes[1];
			$src=$path."/images/ad_test_{$width}x{$height}.jpg";
			if(count($RowsAds)==0)
			{
				$default=array();				
				$default[adTitle_personal]='Title personal goes here ';
				$default[adTitle]='Title gose here ';	
				$default[advertiseId]='0';		
				$RowsAds[]=$default;
			}
			foreach($RowsAds as $ROW){					
				$isize = @getimagesize($path.'/upload/'.$ROW['ad_image']);
				if(is_array($isize))
					$src=$path.'/upload/'.$ROW['ad_image'];
				$ads[]= htmlentities('<a href="'.$path.'/wbk/wbk.php?bk='.__randit().$ROW[advertiseId].__randit().'&s='.__randit().$sites[0].__randit().'&val='.$mdid.'"
				 target="_blank"><img width="'.$width.'" height="'.$height.'" border="0" src="'.$src.'"/></a>');
				 $activeAds[]=$ROW[advertiseId];
			} // End of While								
			$script= "<script language='javascript'>				
					var DOC = top.document;														
					frame=DOC.getElementById('iframe$mdid');					
					frame.style.height=$height;
					frame.style.width=$width;
					</script>";
			$script=htmlentities($script);
			
			break;
		case "thumbnail": //for thumbnail ads			
			// get all attributes  for showing thumbnail ads			
			$thumbCompHandle= empty($ROW_main[thumbCompHandle]) ? "Y" : $ROW_main[thumbCompHandle];
			$thumbCompAge= empty($ROW_main[thumbCompAge]) ? "Y" : $ROW_main[thumbCompAge];
			$thumbComplOCATION= empty($ROW_main[thumbComplOCATION]) ? "Y" : $ROW_main[thumbComplOCATION];
			$thumbCompHeadline= empty($ROW_main[thumbCompHeadline]) ? "Y" : $ROW_main[thumbCompHeadline];
			$thumbCompBrokerLink= empty($ROW_main[thumbCompBrokerLink]) ? "Y" : $ROW_main[thumbCompBrokerLink];
			$thumbCompImage= empty($ROW_main[thumbCompImage]) ? "Y" : $ROW_main[thumbCompImage];
			
			$thumbSize= empty($ROW_main[thumbCompHandle]) ? "60x60" : $ROW_main[thumbSize];
			$thumbView= empty($ROW_main[thumbView]) ? "4" : $ROW_main[thumbView];
			$thumbCustomSize= empty($ROW_main[thumbCustomSize]) ? "N" : $ROW_main[thumbCustomSize];
			$thumbCustomWidth= empty($ROW_main[thumbCustomWidth]) ? "264" : $ROW_main[thumbCustomWidth];
			$thumbCustomHeight= empty($ROW_main[thumbCustomHeight]) ? "215" : $ROW_main[thumbCustomHeight];
			
			$thumbOrientation= empty($ROW_main[thumbOrientation]) ? "Horizontal" : $ROW_main[thumbOrientation];
			$allowNetwork= empty($ROW_main[allowNetwork]) ? "Y" : $ROW_main[allowNetwork];
			$hide_link= empty($ROW_main[hide_link]) ? "N" : $ROW_main[hide_link];
			$backgroundColor= empty($ROW_main[backgroundColor]) ? "#6CDAE7" : $ROW_main[backgroundColor];
			
			// get all of header attributes for thumbnail ads
			$query = "SELECT * FROM thumb_header WHERE adspaceId='$sp'";
			$result = mysql_query($query);
			$rowHeader = mysql_fetch_assoc($result);
			
			$thHeaderFontSize = !empty($rowHeader[thHeaderFontSize]) ? intval($rowHeader[thHeaderFontSize]): "15";
			$thHeaderFontType = !empty($rowHeader[thHeaderFontType]) ? $rowHeader[thHeaderFontType]: "Arial";
			$thHeaderFontColor = !empty($rowHeader[thHeaderFontColor]) ? $rowHeader[thHeaderFontColor]: "#000000";
			$thHeaderAttriBold = !empty($rowHeader[thHeaderAttriBold]) ? $rowHeader[thHeaderAttriBold]: "";
			$thHeaderAttriItalic = !empty($rowHeader[thHeaderAttriItalic]) ? $rowHeader[thHeaderAttriItalic]: "";
			$thHeaderAttriUnderline = !empty($rowHeader[thHeaderAttriUnderline]) ? $rowHeader[thHeaderAttriUnderline]: "";
			$thHeaderAlign = !empty($rowHeader[thHeaderAlign]) ? $rowHeader[thHeaderAlign]: "center";			
			
			// get all of header attributes for thumbnail ads
			$query = "SELECT * FROM thumb_body WHERE adspaceId='$sp'";
			$result = mysql_query($query);
			$rowBody = mysql_fetch_assoc($result);
			
			$thumbBodyFontSize = !empty($rowBody[thumbBodyFontSize]) ? intval($rowBody[thumbBodyFontSize]): "13";
			$thumbBodyFontType = !empty($rowBody[thumbBodyFontType]) ? $rowBody[thumbBodyFontType]: "Arial";
			$thumbBodyFontColor = !empty($rowBody[thumbBodyFontColor]) ? $rowBody[thumbBodyFontColor]: "#000000";
			$thumbBodyAttriBold = !empty($rowBody[thumbBodyAttriBold]) ? $rowBody[thumbBodyAttriBold]: "";
			$thumbBodyAttriItalic = !empty($rowBody[thumbBodyAttriItalic]) ? $rowBody[thumbBodyAttriItalic]: "";
			$thumbBodyAttriUnderline = !empty($rowBody[thumbBodyAttriUnderline]) ? $rowBody[thumbBodyAttriUnderline]: "";
			$thumbBodyAlign = !empty($rowBody[thumbBodyAlign]) ? $rowBody[thumbBodyAlign]: "center";			
			// render HTML 			
			$sizes = explode('x', $thumbSize);
			$thumbWidth = $sizes[0];
			$thumbHeight = $sizes[1];
			$thumbnails = array();
			// style Header text 
			$bodyStyle =array();				
			$bodyStyle[]= "text-align:$thumbBodyAlign";
			$bodyStyle[]= "font-family:$thumbBodyFontType";
			$bodyStyle[]= "font-size:$thumbBodyFontSize";
			$bodyStyle[]= "color:$thumbBodyFontColor";
			$bodyStyle[]= "font-weight:$thumbBodyAttriBold";
			$bodyStyle[]= "text-decoration:$thumbBodyAttriUnderline";
			$bodyStyle[]= "font-style:$thumbBodyAttriItalic";			
			// creating thumbnail items 
			for($i=1;$i<=$thumbView;$i++)
			{
				$src='thumbsrc'.$i;
				$html ="<table border='0' cellspacing='2' cellpadding='0' style='".implode(';',$bodyStyle)."'>";
				$html .= "<TR><td><img src='$src' width='$thumbWidth' height='$thumbHeight'/></td></tr>";
				if($thumbCompHandle=='Y')
					$html .= "<tr><td>Handle</td></tr>";
				if($thumbCompAge=='Y')
					$html .= "<tr><td>Age: 18</td></tr>";
				if($thumbComplOCATION=='Y')
					$html .= "<tr><td>Location</td></tr>";
				if($thumbCompHeadline=='Y')
					$html .= "<tr><td>Headline</td></tr>";				
				$html .= "</table>";
				$thumbnails[]=$html;
			}						
			// formating thumbnail ad
			$html = "<table width='$thumbCustomWidth' height='$thumbCustomHeight' bgcolor='$backgroundColor'  border='0' cellspacing='0' cellpadding='0' >";
			// style Header text 
			$headerStyle =array();				
			$headerStyle[]= "text-align:$thHeaderAlign";
			$headerStyle[]= "font-family:$thHeaderFontType";
			$headerStyle[]= "font-size:$thHeaderFontSize";
			$headerStyle[]= "color:$thHeaderFontColor";
			$headerStyle[]= "font-weight:$thHeaderAttriBold";
			$headerStyle[]= "text-decoration:$thHeaderAttriUnderline";
			$headerStyle[]= "font-style:$thHeaderAttriItalic";
			
			if($thumbOrientation=='Horizontal')
			{	
				//header text 
				$html.="<tr><td colspan='$thumbView' style='".implode(';',$headerStyle)."'>Header Goes Here</td></tr>";
				$html.= "<tr align='center'><td>".implode("</td><td>",$thumbnails)."</td></tr>";				
			}
			else// vertical
			{
				//header text 
				$html.="<tr><td style='".implode(';',$headerStyle)."'>Header Goes Here</td></tr>";
				$html.= "<tr align='center'><td>".implode("</td></tr><tr align='center'><td>",$thumbnails)."</td></tr>";
			}
			$html.="</table>";
						
			//add to ads array
			$ads[] = htmlentities($html);
			$script= "<script language='javascript'>				
					var DOC = top.document;														
					frame=DOC.getElementById('iframe$mdid');
					frame.style.height=$thumbCustomHeight;
					frame.style.width=$thumbCustomWidth;
					</script>";
			$script=htmlentities($script);
			
			break;
		case "customize_commbreak": //for commercial break ads
			//echo "Missing code for generating Commercial Break";
			$html="<div id='commercial_break' style='display:none'>
						<div id='ads_embed' style='position:absolute;top:0px;width:100%;z-index:9999'>
							<div id='adHeader' style='border: 1px solid rgb(204, 204, 204); margin: 0px; padding: 0px;
								width: 100%; height: 63px; background-color: rgb(102, 153, 204); background-image: url();'>
								<table style='width: 100%; height: 100%;' border='0' cellpadding='0' cellspacing='0'>
									<tbody>
										<tr id='headerBody' style='margin: 0px; padding: 0px; vertical-align: middle; height: 41px;'>
											<td style='text-align: left; padding-left: 20px;'>
												<div id='publisherLogo' style='font-size: 19px; font-family: Arial; color: rgb(255, 255, 255);
													font-weight: normal; text-decoration: none; font-style: normal;'>
													Publisher Site Name</div>
											</td>
											<td style='text-align: right; padding-right: 20px;'>
												<div style='display: block;' id='skipButton'>
													<input onclick='top.document.getElementById(\"div$mdid\").innerHTML=\"\";'
													value='Skip Ad &gt;&gt;' style='border-width: 0px; font-family: verdana; font-size: 12px;
														color: rgb(0, 0, 0); font-weight: bold; background-color: transparent; background-image: url(images/cb_skip_ad_button.gif);
														width: 100px; height: 22px;' type='button'>
												</div>
											</td>
										</tr>
										<tr style='vertical-align: middle; text-align: left;'>
											<td colspan='2' style='margin: 0px; padding: 0px;'>
												<div style='background-image: url(images/cb_advertiser_bg.gif); height: 22px; padding-left: 20px;'>
													<span style='font-family: verdana; font-size: 11px; color: rgb(0, 0, 0);'>An Advertisement
														By <span id='advertiserName' style='font-weight: bold;'>Advertiser Name</span>
														<img src='images/arrow_down.png' style='padding-top: 7px;'>
													</span>
												</div>
											</td>
										</tr>
									</tbody>
								</table>
							</div>
						</div>
						<div id='notice' style='color: red; display: none;'>
							Notice: Preview may not display correctly due to security settings in your browser.</div>
					</div>";	
			$ads[]=htmlentities($html);
			$script= "<script language='javascript'>				
						var DOC = top.document;									
						DOC.getElementById('div$mdid').innerHTML=document.getElementById('commercial_break').innerHTML;					
						frame=DOC.getElementById('iframe$mdid');
						frame.style.height=0;
						frame.style.width=0;						
					</script>";
			$script=htmlentities($script);
			break;
		
	}
	
	//echo "Cols: ".$cols." Rows: ".$rows." Adsno: ".$adsno."<br>";
	
	
	$c=0;
	$r=0;
	
	####################################
}else die("Blocked");


function __randit()
{
	$chars = "1023456789";
	srand((double)microtime()*1000000);
	$i = 0;
	$ret = '' ;
	//generates 4 random numbers
	while ($i < 4) {
		$num = rand(1, 9);
		$tmp = substr($chars,$num,1);
		$ret = $ret . $tmp;
		$i++;
	}
	return $ret;
}

function IP2Country($ipAddr)
{
	$location = $ipAddr;
	$q = 'http://api.local.yahoo.com/MapsService/V1/geocode?appid=rlerdorf&location='.rawurlencode($location);
	$resp=file_get_contents($q);
	$xml = simplexml_load_string($resp);
	return $xml->Result[0]->Country;
}
//$ads=array('test','<table><tr><td>Abdul</td></tr></table>',2,3,4,5,6,7,8,9);
if(isset($_POST['Submit']) && $_POST['Submit']!= '')
{
	
	// echo $_POST['Submit'].'<br>';
	$ads=explode('@_@',$_POST['ads']);
	$counter=$_POST['counter'];
	$counter++;
	
	if($_POST['counter'] + (int)1 >= count($ads))
	{
		$counter=0;
	}
	//echo $counter;
	$ad=$ads[$counter];
	if(is_array($activeAds[$counter]))
	{
		//track impression for array ads 
		$SQLimp="INSERT INTO  `advertise_impression_trac` (adsiteId,adspaceId,advertiseId,client_IP,country,visit_time) VALUES";
		$exec=false;
		foreach($activeAds[$counter] as $ata)
		{
			if($ata>0)
			{
				$SQLimp.="(".$sites[0].",".$sp.",".$ata.",'".$_SERVER['REMOTE_ADDR']."','".$country."',NOW()),";	
				$exec=true;
			}
		}
		$SQLimp= trim($SQLimp,",");
		if($exec)
		{
			mysql_query($SQLimp); 
			if(mysql_errno()>0)
				echo "SQL ERROR `advertise_impression_trac`: ".mysql_error();
		}
		
	}
	else if($activeAds[$counter]>0)
	{
		//track impression for array ads 
		if($activeAds[$counter]>0)
		{
			$SQLimp="INSERT INTO  `advertise_impression_trac` (adsiteId,adspaceId,advertiseId,client_IP,country,visit_time) VALUES";
			$SQLimp.="(".$sites[0].",".$sp.",".$activeAds[$counter].",'".$_SERVER['REMOTE_ADDR']."','".$country."',NOW())";	
			mysql_query($SQLimp); 
			if(mysql_errno()>0)
				echo "SQL ERROR `advertise_impression_trac`: ".mysql_error();
		}
	}
}
else
{
	$counter=0;
	$ad=$ads[$counter];
}
if(is_array($activeAds[$counter]))
	{
		//track impression for array ads 
		$SQLimp="INSERT INTO  `advertise_impression_trac` (adsiteId,adspaceId,advertiseId,client_IP,country,visit_time) VALUES";
		$exec=false;
		foreach($activeAds[$counter] as $ata)
		{
			if($ata>0)
			{
				$SQLimp.="(".$sites[0].",".$sp.",".$ata.",'".$_SERVER['REMOTE_ADDR']."','".$country."',NOW()),";	
				$exec=true;
			}
		}
		$SQLimp= trim($SQLimp,",");
		if($exec)
		{
			mysql_query($SQLimp); 
			if(mysql_errno()>0)
				echo "SQL ERROR `advertise_impression_trac`: ".mysql_error();
		}
		
	}
else if($activeAds[$counter]>0)
{
	//track impression for array ads 
	if($activeAds[$counter]>0)
	{
		$SQLimp="INSERT INTO  `advertise_impression_trac` (adsiteId,adspaceId,advertiseId,client_IP,country,visit_time) VALUES";
		$SQLimp.="(".$sites[0].",".$sp.",".$activeAds[$counter].",'".$_SERVER['REMOTE_ADDR']."','".$country."',NOW())";	
		mysql_query($SQLimp); 
		if(mysql_errno()>0)
			echo "SQL ERROR `advertise_impression_trac`: ".mysql_error();
	}
}
?>

<form name="frm_ads" id="frm_ads" method="post" action="">
  <input type="hidden" name="counter" id="counter" value="<?php echo $counter;?>">
  <input type="hidden" name="ads" id="ads" value="<?php echo htmlentities(implode('@_@',$ads));?>">
  <input type="hidden" name="Submit" id="Submit" value="Submit">
</form>
<div>
    <?php echo html_entity_decode($ad); ?>
    <?php echo html_entity_decode($script); ?>
</div>

<script>
//setTimeout("SUBMITfunction();",30000);
function SUBMITfunction()
{
    document.getElementById("frm_ads").submit();
}
</script>